<?php

namespace common\models\DAO;

use Yii;

/**
 * This is the model class for table "mx_product".
 *
 * @property integer $id
 * @property string $title
 * @property string $price
 * @property integer $typeID
 * @property integer $sort
 * @property integer $buySum
 * @property integer $rec
 * @property integer $status
 * @property string $content
 * @property integer $createTime
 * @property integer $adminID
 */
class Product extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'mx_product';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['price', 'typeID', 'sort', 'buySum', 'rec', 'status', 'createTime', 'adminID'], 'integer'],
            [['content', 'createTime', 'adminID'], 'required'],
            [['content'], 'string'],
            [['title'], 'string', 'max' => 50],
        ];
    }

    public function scenarios()
    {
        return [
            'default' => [],
            'add'   => ['title','price', 'typeID', 'sort', 'status','content'],
            'edit'  => ['title','price', 'typeID', 'sort', 'status',  'content'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => '商品名称',
            'price' => '商品价格',
            'typeID' => '商品分类',
            'sort' => '排序',
            'buySum' => '购买次数',
            'rec' => '推荐',//'是否为推荐 0：否 1：是',
            'status' => '状态',//'状态 0:正常 1：下架',
            'content' => '商品描述',
            'createTime' => '添加时间',
            'adminID' => '添加人',
        ];
    }

    public function getProductType()
    {
        return $this->hasOne(ProductType::className(), ['id' => 'typeID']);
    }

    public function getAdmin()
    {
        return $this->hasOne(Admin::className(), ['id' => 'adminID']);
    }

    public function beforeSave($insert)
    {
        if ($insert) {
            $this->createTime = time();
            $this->status = 0;
            $this->rec = 0;
            $this->adminID = Yii::$app->session->get('ADMIN_ID');
        }

        if(in_array($this->scenario, ['add', 'edit', 'check'])){
            $this->price *= 100;
        }



        return parent::beforeSave($insert);
    }
}
